package cn.java8practise.lambda;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.IntConsumer;

/**
 * 方法的引用
 * --p53--57
 * --static的内容组织起来类似于工厂模式
 * <p>
 * Created by 杨志远 on 2017/4/24
 * email faryangsh@163.com.
 */
public class FunctionReference {

    static Map<String, Function<Integer, Fruit>> friutMap = new HashMap<>();

    static {
        friutMap.put("apple", Apple::new);
        friutMap.put("orange", Orange::new);
    }

    public static void main(String[] args) {
        Function<String, Integer> func1 = Integer::parseInt;
        Integer fun1Result = func1.apply("123");
        System.out.println(fun1Result);

        BiPredicate<List<String>, String> fun2 = List::contains;
        List<String> strs = Arrays.asList("123", "12", "124");
        boolean fun2Result = fun2.test(strs, "12");
        System.out.println(fun2Result);

        IntConsumer intConsumer = Integer::new;
        intConsumer.accept(1);
        System.out.print(intConsumer.toString());

        BiFunction<String, Integer, Apple> function3 = (color, weigth) -> new Apple(color, weigth);
        Apple apple1 = function3.apply("apple1", 20);
        //上面function3等价下面的function4
        BiFunction<String, Integer, Apple> function4 = Apple::new;
        //上面function3也等价下面的function5，ConstructorReference是自己自定义的构造函数引用
        ConstructorReference<String, Integer, Apple> function5 = Apple::new;

        //最初的写法
        List<String> strList0 = Arrays.asList("D", "a", "b", "C");
        Comparator<String> stringComparator = (String s1, String s2) -> s1.compareToIgnoreCase(s2);
        strList0.sort(stringComparator);
        System.out.println(strList0);

        //简化写法1,sort()方法中要传Comparator;(s1,s2) -> s1.compareToIgnoreCase(s2)是Comparator的方法的行为参数
        List<String> strList1 = Arrays.asList("D", "a", "b", "C");
        strList1.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
        System.out.println(strList1);

        //简化写法2，compareToIgnoreCase方法的引用签名必须和上下文类型匹配
        List<String> strList2 = Arrays.asList("D", "a", "b", "C");
        strList2.sort(String::compareToIgnoreCase);
        System.out.println(strList2);

        //Function用于接收1个参数，返回结果
        Function<String, Integer> stringToInteger = Integer::parseInt;
        Integer i = stringToInteger.apply("2");
        System.out.println(i);

        Apple apple = (Apple) friutMap.get("Apple".toLowerCase()).apply(23);
        System.out.println(apple.getWeigth());




    }
}
